package com.gin.kotlin.no_gay_alliance.base

import android.app.DownloadManager
import android.content.Context
import android.net.Uri
import android.os.Environment

/**
 * 调用系统下载服务
 */
class DownloadUtils{

    /**
     * 下载选项
     * @property url 地址
     * @property relativePath 文件保存的相对路径（在下载文件夹中）
     * @constructor
     */
    data class DownloadOption(
        val url:String,
        val relativePath:String,
    ){
        /**
         * 构造下载请求
         * @return Request
         */
        fun toRequest() = DownloadManager.Request(Uri.parse(url)).also {
            it.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, relativePath)
            it.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
        }
    }

    companion object{
        /**
         * 获取下载管理器
         * @param context Context
         * @return [DownloadManager]
         */
        fun getDownloadManager(context: Context): DownloadManager =context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        /**
         * 批量下载
         * @param context Context
         * @param options 下载选项
         */
        fun enqueue(context: Context,options:List<DownloadOption>) = options.map { it.toRequest() }.forEach { getDownloadManager(context).enqueue(it) }
    }
}